/*
 * @Author: fangquan
 * @Date: 2020-6-19 10:00:00
 * @Last Modified by: fangquan
 * @Last Modified time: 2020-6-19 10:00:00 
 * @Usage 微信浏览器api封装
 */

import { Toast } from "vant";

import { formatParams } from "./common";

import { checkWechatSDK } from "@/apis/common";

/**
 * 注入微信SDK参数
 */

let initWechatSDK = apis => {
  return new Promise(resolve => {
    checkWechatSDK().then(res => {
      res.data.debug = formatParams().debug == 1 ? true : false;
      res.data.jsApiList = apis;

      wx.config(res.data);
      wx.ready(() => {
        console.log("---- 微信SDK初始化成功 ----");
        console.log(`初始化API列表：${res.data.jsApiList.toString()}`);
        resolve();
      })
    })
  })
}

export default {
  /**
   * @method share 微信分享
   * @param {object} params title标题、desc简介、imgUrl缩略图、link链接
   */
  share: (params) => {
    return new Promise((resolve, reject) => {
      initWechatSDK(["onMenuShareTimeline", "onMenuShareAppMessage"]).then(() => {
        console.log("配置分享：");
        console.log(params);
        wx.onMenuShareTimeline({
          ...params,
          success: res => {
            resolve(res);
          }
        });

        wx.onMenuShareAppMessage({
          ...params,
          success: res => {
            resolve(res);
          }
        })
      })
    })
  },

  /**
   * @method pay 支付
   * param {object} params 支付参数
   */
  pay: (params) => {
    console.log("支付参数：");
    console.log(params);
    return new Promise((resolve, reject) => {
      initWechatSDK(["chooseWXPay"]).then(() => {
        console.log("开始调起支付");
        wx.chooseWXPay({
          ...params,
          success: res => {
            resolve(res);
            Toast("支付成功");
          },
          fail: err => {
            reject(err);
            Toast("支付失败");
          },
          cancel: err => {
            reject(err);
            Toast("已取消支付");
          }
        })
      })
    })
  },

  /**
   * @method initAudio 初始化音频API
   */
  initAudio () {
    return new Promise((resolve, reject) => {
      initWechatSDK(["startRecord", "stopRecord", "playVoice", "uploadVoice", "onVoiceRecordEnd", "stopVoice", "onVoicePlayEnd"], () => {
        resolve();
      })
    })
  },

  /**
   * @method：获取微信内置收货地址
   */
  address () {
    return new Promise((resolve, reject) => {
      initWechatSDK(["editAddress"]).then(() => {
        wx.openAddress({
          success: res => {
            resolve(res);
          }
        })
      })
    })
  }
}